"""
Beautiful Soup4基本使用方法
Beautiful Soup对象种类
Tag:
    遍历文档树
        1.通过tag名字获取节点，如：soup.tag1.tag2.tag3，这种方式智只能获取第一个标签
        2.通过.contents 可以获取tag下面的子节点的列表形式，字符串没有.contents
        3.通过.children可以对tag的子节点进行循环遍历
        4.
Name:
Attributes:
"""
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister sister2" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

# 创建Beautiful对象
soup = BeautifulSoup(html_doc, features="lxml")
# print(soup.prettify())

# 获取标签
title = soup.title
title2 = soup.head.title
print("----title-----")
print(title)
print(title.name)
print(title.parent.name)
print(title.string)
print("----title2-----")
print(title2)
print(title2.name)
print(title2.parent.name)
print(title2.string)
# 获取第一个标签
p = soup.p
print(p)
print(p.name)
print(p['class'])

# 获取所有标签
a_lst = soup.find_all("a")
print(a_lst)

# 根据属性查找
print("-----------以下是根据属性查找的用法------------")
link1 = soup.find(id="link1")
print(link1)

link_lst = soup.find_all(attrs={"class": "sister", "id": "link2"})
print(link_lst)

# link_class_lst = soup.find_all(attrs={"class": "sister"})
link_class_lst = soup.find_all(class_="sister")
print(link_class_lst)

# .contents 和 .children 用法
print("-----------以下是.contents 和 .children 用法------------")
p_lst = soup.body.contents
print(p_lst)
for p in p_lst:
    print(f"tag:{p},text:{p.string}")
